package com.neusoft.neuiotms.dcom.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.converter.FunctionalGroupConverter;
import com.neusoft.neuiotms.dcom.converter.FunctionalUserConverter;
import com.neusoft.neuiotms.dcom.dto.FunctionalGroupDTO;
import com.neusoft.neuiotms.dcom.dto.FunctionalUserDTO;
import com.neusoft.neuiotms.dcom.model.FunctionalGroup;
import com.neusoft.neuiotms.dcom.model.FunctionalUser;
import com.neusoft.neuiotms.dcom.repository.FunctionalGroupRepository;
import com.neusoft.neuiotms.dcom.repository.FunctionalUserRepository;
import com.neusoft.neuiotms.dcom.service.FunctionalGroupService;

@Service
public class FunctionalGroupServiceImpl implements FunctionalGroupService {

    @Autowired
    private FunctionalGroupConverter functionalGroupConverter;
    @Autowired
    private FunctionalGroupRepository functionalGroupRepository;
    @Autowired
    private FunctionalUserRepository functionalUserRepository;
    @Autowired
    private FunctionalUserConverter functionalUserConverter;

    @Override
    public List<FunctionalGroupDTO> index(final Searchable searchable) {
        final List<FunctionalGroup> models = this.functionalGroupRepository.index(searchable);
        return this.functionalGroupConverter.toListDTO(models);
    }

    @Override
    public Page<FunctionalGroupDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<FunctionalGroup> result = this.functionalGroupRepository.search(pageable, searchable);
        return this.functionalGroupConverter.toPageDTO(result);
    }

    @Override
    public Page<FunctionalUserDTO> userSearch(final Pageable pageable, final Searchable searchable) {
        final Page<FunctionalUser> result = this.functionalUserRepository.search(pageable, searchable);
        return this.functionalUserConverter.toPageDTO(result);
    }

    @Override
    public FunctionalGroupDTO create(final FunctionalGroupDTO dto) {

        // 校验每个人只能在一个职能组
        final List<String> errorList = new ArrayList<>();
        dto.getUsers().stream().map(k -> {
            final FunctionalUser user = this.functionalUserRepository.findByCode(k.getCode());
            if (null != user) {
                return user.getName();
            } else {
                return null;
            }
        }).filter(s -> null != s).forEach(errorList::add);

        if (!errorList.isEmpty()) {
            final StringBuilder b = new StringBuilder();
            errorList.stream().forEach(k -> {
                b.append(k + " ");
            });
            throw new UnitedException("[" + b.toString() + "]这些人员已经存在别的组");
        }

        final FunctionalGroup model = this.functionalGroupConverter.toModel(dto);
        this.functionalGroupRepository.save(model);
        return this.functionalGroupConverter.toDTO(model);
    }

    @Override
    public FunctionalGroupDTO update(final Long id, final FunctionalGroupDTO dto) {

        // 校验每个人只能在一个职能组
        final List<String> errorList = new ArrayList<>();
        dto.getUsers().stream().map(k -> {
            final FunctionalUser user = this.functionalUserRepository.findByCode(k.getCode());
            if ((null != user) && (user.getGroup().getId().longValue() != id.longValue())) {
                return user.getName();
            } else {
                return null;
            }
        }).filter(s -> null != s).forEach(errorList::add);

        if (!errorList.isEmpty()) {
            final StringBuilder b = new StringBuilder();
            errorList.stream().forEach(k -> {
                b.append(k + " ");
            });
            throw new UnitedException("[" + b.toString() + "]这些人员已经存在别的组");
        }

        FunctionalGroup model;
        try {
            model = this.functionalGroupRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.functionalGroupConverter.toModel(dto);
        this.functionalGroupRepository.save(model);
        return this.functionalGroupConverter.toDTO(model);
    }

    @Override
    public FunctionalGroupDTO details(final Long id) {

        FunctionalGroup model;

        try {
            model = this.functionalGroupRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        return this.functionalGroupConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {

        try {
            this.functionalGroupRepository.deleteById(id);
        } catch (final Exception e) {
            throw new UnitedException("此职能已经关联巡检，不能删除！");
        }

    }

}
